import { defineStore } from "pinia";
// 本地存储：读取、删除、存储
import { getToken, removeToken, setToken } from "../utils/token-utils";
// 类型
import type { UserInfoState } from "./interface";
import { ElMessage } from "element-plus";
import { staticRoutes } from "@/router/routes";
import { reqUserInfo, reqUserLogin, reqUserLogout } from "@/api/acl";

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore("userInfo", {
  state: (): UserInfoState => ({
    token: getToken() as string, // token
    name: "", //用户名
    avatar: "", //用户头像
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      const result = await reqUserLogin({ username, password });
      // 本地存储 持久化 token
      setToken(result.token);
      // pinia 仓库持久化
      this.token = result.token;
    },

    // 获取用户信息
    async getInfo() {
      const userInfo = await reqUserInfo();
      this.name = userInfo.name;
      this.avatar = userInfo.avatar;
      // 菜单来自 staticRoutes
      this.menuRoutes = staticRoutes;
    },

    // 登出
    async reset() {
      await reqUserLogout();
      // 删除 local 中保存的token
      removeToken();
      // 提交重置用户信息的mutation
      this.token = "";
      this.name = "";
      this.avatar = "";
    },
  },
});
